package logic.action.base;

import java.util.HashMap;

import base.tina.core.task.AbstractListener;
import base.tina.core.task.infc.IDisposable;
import base.tina.core.task.infc.ITaskListener;

import com.tgx.tina.android.ipc.framework.BaseActivity;


/**
 * @Title: AbstractActionA.java
 * @Package logic.extenal.android.actions
 * @Description: TODO(添加描述)
 * @author Dai Zhipeng
 * @date 2012-10-16 上午10:48:55
 */
public abstract class AsyncUIAction<T extends BaseActivity>
        extends
        AbstractListener
        implements
        IDisposable
{
	private final static HashMap<String, AsyncUIAction<? extends BaseActivity>> gUiActions = new HashMap<String, AsyncUIAction<? extends BaseActivity>>();
	
	public final static AsyncUIAction<?> getSelf(Class<? extends AsyncUIAction<?>> clazz) {
		return gUiActions.get(clazz.getName());
	}
	
	public final static AsyncUIAction<?> getSelf(String className) {
		return gUiActions.get(className);
	}
	
	protected T bActivity;
	
	public AsyncUIAction(T baseActivity) {
		this(baseActivity, false);
	}
	
	public AsyncUIAction(T baseActivity, boolean single) {
		super();
		bActivity = baseActivity;
		if (bActivity.mAService == null) throw new NullPointerException();
		if (single)
		{
			AsyncUIAction<? extends BaseActivity> asyncUIAction = gUiActions.get(this.getClass().getName());
			if (asyncUIAction != null)
			{
				ITaskListener iTaskListener = baseActivity.mAService.removeListener(asyncUIAction.getBindSerial());
				base.tina.core.log.LogPrinter.w(null, this.getClass().getName() + " reentrant add! plz check your logic~");
			}
			gUiActions.put(this.getClass().getName(), this);
		}
		boolean success = bActivity.mAService.addListener(this);
		if (!success) System.err.println("add ITaskListener :" + this + " failed");
		create();
	}
	
	/**
	 * 一个Action被初始化时调用，可以在此处初始化一些数据
	 */
	public abstract void create();
	
	/**
	 * 一个Action的执行入口，生命周期的开始
	 * 
	 * @param e
	 */
	public abstract <E> void start(E e);
	
	/**
	 * 一个Action的执行入口，生命周期的开始,更改Action的上下文对象，在多个Activity切换时候，建议使用这个方法start
	 * 
	 * @param e
	 */
	public <E> void start(E e, T baseActivity) {
		bActivity = baseActivity;
		start(e);
	}
	
	public void finish() {
		bActivity.mAService.removeListener(getBindSerial());
		enabled = false;
		dispose();
	}
	
	@Override
	public boolean isDisposable() {
		return !enabled;
	}
	
	@Override
	public void dispose() {
		bActivity = null;
	}
	
	protected boolean enabled = true;
	
}
